package com.gaofei.sysmanager.service.impl;


import com.gaofei.sysmanager.common.ResponseVo;
import com.gaofei.sysmanager.domain.EmailInfo;
import com.gaofei.sysmanager.service.EmailService;
import gui.ava.html.renderer.ImageRenderer;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

/**
 * @Classname EmailServiceImpl
 * @Description TODO
 * @Date 2022/4/15 11:21
 * @Created by 93173
 */
@Service
public class EmailServiceImpl implements EmailService {
    Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Override
    public String sendEmail(EmailInfo emailInfo) {

        Properties properties = new Properties();
        properties.put("mail.smtp.host", emailInfo.getHost());
        properties.put("mail.smtp.auth", "true");
        Session session = Session.getInstance(properties);
        Message emailMessage = new MimeMessage(session);

        try {
            //发送人
            InternetAddress sender = new InternetAddress(emailInfo.getFrom()); //发送者账号
            sender.setPersonal(MimeUtility.encodeText(emailInfo.getNickname()));//昵称
            emailMessage.setFrom(sender);

            //收件人
            InternetAddress to = new InternetAddress(emailInfo.getAddress());//收件人账号
            emailMessage.setRecipient(Message.RecipientType.TO, to);

            //消息
            emailMessage.setSubject(MimeUtility.encodeText(emailInfo.getSubject()));//邮件主题
            emailMessage.setSentDate(new Date());
            MimeMultipart mimeMultipart = new MimeMultipart("mixed");//指定为混合关系
            emailMessage.setContent(mimeMultipart);

            //邮件内容
            MimeBodyPart htmlPart = new MimeBodyPart();
            htmlPart.setContent(emailInfo.getContent()+"<img src='cid:a'>", "text/html;charset=UTF-8");

            //组装内容
            mimeMultipart.addBodyPart(htmlPart);

         /*   // 创建图片
            MimeBodyPart img = new MimeBodyPart();

            DataHandler dh = new DataHandler(new FileDataSource(""));//图片路径
            img.setDataHandler(dh);
            // 创建图片的一个表示用于显示在邮件中显示
            img.setContentID("a");
*/
            /*MimeBodyPart img2 = new MimeBodyPart();
            DataHandler dh2 = new DataHandler(new FileDataSource("E:\\iphone\\lcxq1.png"));//第二张图片路径
            img2.setDataHandler(dh2);
            img2.setContentID("b");*/

        /*    MimeMultipart mm = new MimeMultipart();
            mm.addBodyPart(htmlPart);
//            mm.addBodyPart(img);
            mm.setSubType("related");// 设置正文与图片之间的关系*/

            //组装附件
            /*if (emailInfo.getFilePath() != null && !emailInfo.getFilePath().equals("")) {

                MimeBodyPart file = new MimeBodyPart();
                FileDataSource file_datasource = new FileDataSource(emailInfo.getFilePath());
                DataHandler dh = new DataHandler(file_datasource);
                file.setDataHandler(dh);
                // 附件区别内嵌内容的一个特点是有文件名，为防止中文乱码要编码
                file.setFileName(MimeUtility.encodeText(dh.getName()));
                mimeMultipart.addBodyPart(file);
            }*/
//            emailMessage.setContent(mm);
            emailMessage.saveChanges();
            Transport transport = session.getTransport("smtp");
            transport.connect(emailInfo.getHost(), Integer.parseInt(emailInfo.getPort()), emailInfo.getFrom(), emailInfo.getPassword());
            transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
            transport.close();
            return "邮件发送成功！";
        } catch (AddressException e) {
            logger.error("邮件发送失败，错误原因：" + e.getMessage());
            return "请检查邮箱地址:";
        } catch (UnsupportedEncodingException e) {
            logger.error("邮件发送失败，错误原因：" + e.getMessage());
            return "转码异常，请查看详细信息";
        } catch (NoSuchProviderException e) {
            logger.error("邮件发送失败，错误原因：" + e.getMessage());
            return "邮件发送失败，详细错误原因：";
        } catch (MessagingException e) {
            logger.error("邮件发送失败，错误原因：" + e.getMessage());
            return "邮件发送失败，有可能的问题为服务器url不存在或附件不存在，具体请看详细信息：";
        }
    }



}
